package cn.qu.dockman.mgr.controller;

import cn.qu.dockman.mgr.entity.Host;
import cn.qu.dockman.mgr.service.ContainerService;
import cn.qu.dockman.mgr.ws.SendingQueue;
import cn.qu.dockman.protocol.command.server.ContainerServiceCommand;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static cn.qu.dockman.protocol.command.server.ContainerServiceCommand.ContainerServiceBody;
import static cn.qu.dockman.protocol.command.server.ContainerServiceCommand.Type;

/**
 * Created by zh on 17/3/7.
 */
@RestController
@RequestMapping("/container")
public class ContainerController {

    @Autowired
    private ContainerService containerService;

    @Autowired
    private SendingQueue sendingQueue;

    @RequestMapping(value = "/{hostId}", method = RequestMethod.GET)
    public PageInfo<Host> findAll(@PathVariable int hostId,
                                  @RequestParam(defaultValue = "1") int pageNo,
                                  @RequestParam(defaultValue = "10") int pageSize) {

        return PageHelper.startPage(pageNo, pageSize).doSelectPageInfo(() -> containerService.findByHostId(hostId));
    }

    @RequestMapping(value = "/start", method = RequestMethod.POST)
    public void start(@RequestBody Service service) {

        ContainerServiceBody body = new ContainerServiceBody();
        body.setType(Type.START);
        body.setContainerId(service.getContainerId());
        sendingQueue.send(service.getHostId(), ContainerServiceCommand.create(new ContainerServiceBody[]{body}));
    }

    @RequestMapping(value = "/stop", method = RequestMethod.POST)
    public void stop(@RequestBody Service service) {

        ContainerServiceBody body = new ContainerServiceBody();
        body.setType(Type.STOP);
        body.setContainerId(service.getContainerId());
        sendingQueue.send(service.getHostId(), ContainerServiceCommand.create(new ContainerServiceBody[]{body}));
    }

    public static class Service {
        private String containerId;
        private Integer hostId;

        public String getContainerId() {
            return containerId;
        }

        public void setContainerId(String containerId) {
            this.containerId = containerId;
        }

        public Integer getHostId() {
            return hostId;
        }

        public void setHostId(Integer hostId) {
            this.hostId = hostId;
        }
    }
}
